package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.redis.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.redis.util.RedisKeys;
import cn.wolfcode.luowowo.repository.UserInfoRepository;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.AssertUtils;
import cn.wolfcode.luowowo.util.Consts;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private IUserInfoRedisService redisService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Override
    public UserInfo get(String id) {
        return  userInfoRepository.findById(id).orElse(null);
    }

    @Override
    public boolean checkPhone(String phone) {
        UserInfo byPhone = userInfoRepository.findByPhone(phone);
        return byPhone != null;
    }

    @Override
    public void sendVerifyCode(String phone, String ssmUrl, String ssmLogo, String ssmAppKey) {
        //生成验证码
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
        //发送短信
        StringBuilder builder = new StringBuilder(100);
        builder.append("你好，验证码是：").append(code).append(",请在").append(Consts.VERIFY_CODE_VAI_TIME).append("分钟内完成验证");
        //真实短信
//        String url = "https://way.jd.com/chonry/smsnotice?sign=【骡窝窝】"+
//        "&mobile="+phone+"&content="+builder.toString()+"。&appkey=5b7f55ecc18a57b8a2fab90c3f787741";
        //java发送HTML请求路径的对象
        RestTemplate template = new RestTemplate();
        String sr = template.getForObject(ssmUrl, String.class,ssmLogo,phone,builder.toString(),ssmAppKey);
        if (!sr.contains("查询成功")){
            throw new LogicException("发送失败");
        }
        System.out.println(sr);
        System.out.println(builder.toString());
        redisService.sendVerifyCode(phone,code);

    }

    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
       //判断参数是否为空
        AssertUtils.hesLength(phone,"手机号码不能为空");
        AssertUtils.hesLength(nickname,"用户名不能为空");
        AssertUtils.hesLength(password,"密码不能为空");
        AssertUtils.hesLength(rpassword,"确认密码不能为空");
        AssertUtils.hesLength(verifyCode,"验证码不能为空");
        //都不为空，执行保存
        //判断号码是否被改，如果用户先发验证码在用POSTman去修改电话号码，会导致bug
        if(this.checkPhone(phone)){
            throw new LogicException("电话号码已存在");
        }
        //判断密码和确认密码是否一致
        if(!password.equals(rpassword)){
            throw new LogicException("密码和确认密码不正确");
        }
        //判断验证码是否正确，去缓存里取出来，在哪来比较
        String sb = redisService.getVerifyCode(phone);
        if(!sb.equals(verifyCode)){
            throw new LogicException("验证码不正确");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setEmail("");
        userInfo.setCity("");
        userInfo.setPassword(password);
        userInfo.setGender(0);
        userInfo.setInfo("");
        userInfo.setLevel(1);
        userInfo.setState(0);
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfoRepository.save(userInfo);
    }


    @Override
    public String setToken(String user) {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisService.setTonken(token,user);
        return token;
    }

    @Override
    public UserInfo login(String username, String password) {
        UserInfo user = userInfoRepository.findByPhoneAndPassword(username, password);
        if (user == null){
            throw new LogicException("用户名或者密码错误");
        }
        return user;
    }



    @Override
    public UserInfo getUserByToken(String token) {

        String user = redisService.getUserByToken(token);
        UserInfo userInfo = JSON.parseObject(user, UserInfo.class);
        if(userInfo == null){
            return null;
        }
        redisTemplate.expire(RedisKeys.VERIFY_TOKEN.join(token),RedisKeys.VERIFY_TOKEN.getTime(), TimeUnit.SECONDS);
        return userInfo;
    }

//    @Override
//    public UserInfo findByToken(String token) {
//        UserInfo userInfo = userInfoRepository.findByToken(token);
//        return userInfo;
//    }

//    @Override
//    public JsonResult sendVerifyCode(String phone) {
//        String sb = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
//        redisTemplate.opsForValue().set("userInfo:phone" + phone, sb);
//        String s = redisTemplate.opsForValue().get("userInfo:phone" + phone);
//        System.out.println(s);
//        return new JsonResult();
//    }
}
